/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedFaceData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { ctx2 } from '../../../../../module';
import { usePlaneContext } from './PlaneContext';
import { ChildPlaneCommandProps } from './types';

type FormData = {
  plane?: pickedFaceData;
  point?: pickedVertexData;
};

type Params = {
  mode: 'point-tr';
  plane: string;
  point: string;
};

export const PlanePoint = ({
  props,
  onClose,
  editDxid,
}: ChildPlaneCommandProps) => {
  const [formData, setFormData] = useState<FormData>({});
  const { sharedPlane, sharedPoint, setSharedPlane, setSharedPoint } =
    usePlaneContext();

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({});
      return;
    }

    const { plane, point } = props.params as Params;

    await initEditDependency([plane, point]);

    const planeObj = picker.generatePickObjByPickID(plane) as pickedFaceData;
    const pointObj = picker.generatePickObjByPickID(point) as pickedVertexData;

    setFormData({
      point: pointObj,
      plane: planeObj,
    });

    setSharedPlane(planeObj);
    setSharedPoint(pointObj);
  }, [editDxid]);

  useEffect(() => {
    if (sharedPlane && !formData.plane) {
      setFormData((prev) => ({ ...prev, plane: sharedPlane }));
    }
    if (sharedPoint && !formData.point) {
      setFormData((prev) => ({ ...prev, point: sharedPoint }));
    }
  }, [sharedPlane, sharedPoint]);

  const isFormDataValid = () => {
    const { plane, point } = formData;

    return plane != null && point != null;
  };

  useEffect(() => {
    preview();
  }, [formData]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);

    ctx2.viewer.requestRender();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-plane-point', {
      commandName: 'CreatePlane',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { plane, point } = formData;

    return confirmCommand(
      {
        a: {
          mode: 'point-tr',
          plane: plane.meshId,
          point: point.vertexId,
        },
      },
      preview,
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      plane: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
      point: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        if (v.plane && v.plane !== formData.plane) {
          setSharedPlane(v.plane);
        }
        if (v.point && v.point !== formData.point) {
          setSharedPoint(v.point);
        }

        setFormData(v);
      }}
      extraUiSchema={{
        plane: {
          'ui:placeholder': '请输入平面',
          'ui:autofocus': true,
        },
        point: {
          'ui:placeholder': '请输入通过点',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
